#! /bin/bash 
# 生成组件模板
NAME=$1

FILE_PATH=$(cd "$(dirname "${BASH_SOURCE[0]}")/../packages" && pwd)

re="[[:space:]]+"

if [ "$#" -ne 1 ] || [[ $NAME =~ $re ]] || [ "$NAME" == "" ]; then
  echo "Usage: pnpm gc \${name} with no space"
  exit 1
fi

DIRNAME="$FILE_PATH/zlyun-vue/src/components/$NAME"
INPUT_NAME=$NAME

if [ -d "$DIRNAME" ]; then
  echo "$NAME component already exists, please change it"
  exit 1
fi

NORMALIZED_NAME=""
for i in $(echo $NAME | sed 's/[_|-]\([a-z]\)/\ \1/;s/^\([a-z]\)/\ \1/'); do
  C=$(echo "${i:0:1}" | tr "[:lower:]" "[:upper:]")
  NORMALIZED_NAME="$NORMALIZED_NAME${C}${i:1}"
done
NAME=$NORMALIZED_NAME

mkdir -p "$DIRNAME"
mkdir -p "$DIRNAME/style"
mkdir -p "$DIRNAME/src"
mkdir -p "$DIRNAME/__tests__"

cat > $DIRNAME/src/index.vue <<EOF
<template>
  <div>
    <slot></slot>
  </div>
</template>
<script lang='ts' setup>
import "../style/index.scss";
import { reactive,toRefs,onMounted } from 'vue'
import { ${NAME,}Props } from "./types";
defineOptions({
  name: 'Z${NAME}',
})
const props = defineProps(${NAME,}Props);

</script>
EOF

cat > $DIRNAME/src/types.ts <<EOF
import { ExtractPropTypes, defineComponent } from "vue";

export const ${NAME}Props = defineComponent({
  props:{
    color: {
      type:String,
      default:""
    },
  }
})
export const ${NAME,}Props = ${NAME}Props.props

export type ${NAME}Props = ExtractPropTypes<typeof ${NAME}Props>;

EOF

cat > $DIRNAME/style/index.scss <<EOF

EOF

cat <<EOF >"$DIRNAME/index.ts"
import { withInstall } from "@zlyun-vue/utils";

import ${NAME} from './src/index.vue'

export const Z${NAME} = withInstall(${NAME});
export default Z${NAME};

export * from "./";

EOF

cat > $DIRNAME/__tests__/$INPUT_NAME.spec.ts <<EOF
import { describe, expect, test } from "vitest";
import { mount } from '@vue/test-utils'
import $NAME from '../src/index.vue'

const AXIOM = 'Hellow World'

describe('$NAME.vue', () => {
  test('render test', () => {
    const wrapper = mount($NAME, {
      slots: {
        default: AXIOM,
      },
    })
    expect(wrapper.text()).toEqual(AXIOM)
  })
})
EOF
